package com.jaks.xpense;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.jaks.xpense.data.Expenses;
import com.jaks.xpense.data.PaymentTypes;
import com.jaks.xpense.data.entities.Expense;
import com.jaks.xpense.data.entities.PaymentType;
import com.jaks.xpense.data.entities.TableEntity;
import com.jaks.xpense.data.entities.Tag;
import com.jaks.xpense.utils.FlowLayout;
import com.jaks.xpense.utils.Globals;
import com.jaks.xpense.utils.WidgetUtils;

public class EditExpenseActivity extends Activity implements OnClickListener {

	private PaymentTypes paymentTypes;
	private Expenses expenses;

	private ArrayList<PaymentType> paymentTypesList;
	private long id;
	private long paymentTypeId;
	private long[] selectedTagIds;

	private TextView expenseDate;
	private EditText amount;
	private TextView paidThru;
	private EditText comments;
	private FlowLayout tagsLayout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		id = 0;
		paymentTypeId = 0;
		paymentTypes = new PaymentTypes(this);
		expenses = new Expenses(this);

		// UI Part
		setContentView(R.layout.addexpense);

		expenseDate = (TextView) findViewById(R.id.expenseDate);
		amount = (EditText) findViewById(R.id.amountText);
		paidThru = (TextView) findViewById(R.id.paidThru);
		comments = (EditText) findViewById(R.id.commentsText);
		tagsLayout = (FlowLayout) findViewById(R.id.tagsLayout);
		ImageView addTags = (ImageView) findViewById(R.id.addTags);
		TextView saveExpense = (TextView) findViewById(R.id.saveExpense);

		expenseDate.setOnClickListener(this);
		paidThru.setOnClickListener(this);
		addTags.setOnClickListener(this);
		saveExpense.setOnClickListener(this);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			id = extras.getLong(TableEntity.Id);
			setTitle(R.string.editExpense);
		} else {
			setTitle(R.string.newExpense);
		}
		registerForContextMenu(paidThru);
		refreshPaymentTypes();
		populate();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	private void populate() {
		if (id == 0) {
			expenseDate.setText(Globals.toDateText(Calendar.getInstance()));

			if (paymentTypesList.size() > 0) {
				setPaymentType(paymentTypesList.get(0));
			}
			selectedTagIds = null;
			showTagCloud(null);

			return;
		}

		Expense expense = (Expense) expenses.read(id);
		expenseDate.setText(expense.getExpenseDate());
		amount.setText(String.valueOf(expense.getAmount()));
		comments.setText(expense.getComments());
		setPaymentType(expense.getPaymentType());

		String[] selectedTagNames = null;
		ArrayList<Tag> tags = expenses.getTags(id);
		if (tags.size() > 0) {

			selectedTagIds = new long[tags.size()];
			selectedTagNames = new String[tags.size()];

			int index = 0;
			for (Tag tag : tags) {
				selectedTagIds[index] = tag.getId();
				selectedTagNames[index] = tag.getName();
				index++;
			}
		}
		showTagCloud(selectedTagNames);
	}

	private void refreshPaymentTypes() {
		paymentTypesList = paymentTypes.readAllToList();
	}

	private void setPaymentType(long id) {

		for (PaymentType type : paymentTypesList) {
			if (type.getId() == id) {
				setPaymentType(type);
				break;
			}
		}
	}

	private void setPaymentType(PaymentType type) {
		paymentTypeId = type.getId();
		paidThru.setText(getString(R.string.paidThru) + " " + type.getName());
	}

	private void selectTags() {
		Intent intent = new Intent(this, SelectTagsActivity.class);
		intent.putExtra(Globals.SelectedTagIds, selectedTagIds);
		startActivityForResult(intent, 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode != RESULT_OK)
			return;

		selectedTagIds = data.getLongArrayExtra(Globals.SelectedTagIds);
		String[] selectedTagNames = data.getStringArrayExtra(Globals.SelectedTagNames);

		showTagCloud(selectedTagNames);
	}

	private void showTagCloud(String[] selectedTagNames) {
		tagsLayout.removeAllViews();

		if (selectedTagNames == null)
			selectedTagNames = new String[] { getString(R.string.noTagsSelected) };

		for (int i = 0; i < selectedTagNames.length; i++) {
			tagsLayout.addView(getTagView(selectedTagNames[i]), new FlowLayout.LayoutParams(4, 4));
		}
	}

	private TextView getTagView(String tagName) {
		TextView textView = new TextView(this);
		textView.setText(tagName);
		textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
		textView.setPadding(3, 2, 3, 2);
		textView.setTextColor(Color.parseColor(Globals.TagForegroundColor));
		textView.setBackgroundColor(Color.parseColor(Globals.TagBackgroundColor));
		textView.setSingleLine(true);

		return textView;
	}

	private boolean saveExpense() {

		String date = expenseDate.getText().toString();
		String comment = comments.getText().toString();
		if (amount.getText().toString().trim().length() == 0)
			return false;
		double expenseAmount = Double.parseDouble(amount.getText().toString());
		if (expenseAmount == 0.0)
			return false;

		Expense expense = new Expense(id, date, paymentTypeId, expenseAmount, comment);
		if (id == 0) {
			id = expenses.create(expense);
		} else {
			expenses.update(expense);
		}

		if (id > 0) {
			expenses.setTags(id, selectedTagIds);
		}

		return true;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		// menu.clear();
		menu.setHeaderTitle(R.string.paymentTypes);
		menu.setHeaderIcon(null);
		for (PaymentType paymentType : paymentTypesList) {
			menu.add(0, (int) paymentType.getId(), 0, paymentType.getName());
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		setPaymentType(item.getItemId());
		return true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		paymentTypes.close();
		expenses.close();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
			case R.id.expenseDate:
				Calendar calendar = Globals.toCalendar(expenseDate.getText().toString());
				int year = calendar.get(Calendar.YEAR);
				int month = calendar.get(Calendar.MONTH);
				int day = calendar.get(Calendar.DAY_OF_MONTH);

				DatePickerDialog datePicker = new DatePickerDialog(this, dateSetListener, year, month, day);
				datePicker.show();
				break;
			case R.id.paidThru:
				openContextMenu(paidThru);
				break;
			case R.id.addTags:
				selectTags();
				break;
			case R.id.saveExpense:
				if (saveExpense()) {

					double todayTotal = expenses.getTodaysTotal();
					double balance = expenses.getBalance();
					WidgetUtils.sendUpdateToWidget(this, todayTotal, balance);

					setResult(RESULT_OK);
					finish();
				}
				break;
		}
	}

	private final DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int month, int day) {
			expenseDate.setText(Globals.toDateText(year, month, day));
		}
	};
}
